//
//  SXPphotoCollectionView.swift
//  weibo
//
//  Created by shixinPeng on 16/3/7.
//  Copyright © 2016年 shixinPeng. All rights reserved.
//

import UIKit
import SnapKit

let photoviewMargin:CGFloat = 10
let photoItemMargin:CGFloat = 5
let SXPphotoCollectionViewCell = "SXPphotoCollectionViewCell"
class SXPphotoCollectionView: UICollectionView, UICollectionViewDataSource, UICollectionViewDelegate, photoCellDelagate{
    /// 存放照片的数组
    var iamges = [UIImage]()
    /// 添加照片的闭包
    var imageClosure:(() -> ())?

    var flowlayout = UICollectionViewFlowLayout()
    
    //重写初始化方法
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
            super.init(frame: frame, collectionViewLayout: flowlayout)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //2.设置私有方法,
    private func setupUI(){
    
        self.backgroundColor = UIColor.orangeColor()
        //设置数据源和代理
        dataSource = self
        delegate = self
        
        //注册cell
        registerClass(photoCell.self, forCellWithReuseIdentifier: SXPphotoCollectionViewCell)
        
        let cellItemWH = (kUISCREEN_W - 2 * photoviewMargin - 2 * photoItemMargin)/3
        
        flowlayout.itemSize = CGSizeMake(cellItemWH, cellItemWH)
        flowlayout.minimumInteritemSpacing = photoItemMargin
        flowlayout.minimumLineSpacing = photoItemMargin
        flowlayout.scrollDirection = .Vertical
        
    }
    
   func addImage(image:UIImage){
        
        self.iamges.append(image)
        
        self.reloadData()
    }
  //实现代理方法
    func deletePhoto(index: Int) {
        //移除对应的照片
        self.iamges.removeAtIndex(index)
        self.reloadData()
    }
    
}


//MARK: --数据源方法
extension SXPphotoCollectionView {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if iamges.count == 9 || iamges.count == 0{
            return iamges.count
        }else{
        return iamges.count + 1
        }
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = dequeueReusableCellWithReuseIdentifier(SXPphotoCollectionViewCell, forIndexPath: indexPath) as! photoCell
        
        
        if indexPath.item == iamges.count {
            cell.iconImage = nil
        }else{
            cell.iconImage = self.iamges[indexPath.item]
            
        }
        
        //设置代理
        cell.delegate = self
        
        cell.index = indexPath
        
        return cell
    }
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        /*
        indexPath.item是从0开始的
        count是从1开始的.
        item==count 就等于等于多出图片数组的那一个
        
        
        */
        //判断是否是最后一个,如果是最后一个,调用打开相册的方法
        if indexPath.item == iamges.count {
            imageClosure?()
        }
    }
    
}

//MARK: --cell的代理方法
protocol photoCellDelagate :NSObjectProtocol{
    //删除图片的方法
    func deletePhoto(index: Int)
}

//MARK: --自定义照片cell
class photoCell: UICollectionViewCell {
    
    //定义一个代理属性
    weak var delegate: photoCellDelagate?
    
    //记录当前的cell的index
    var index: NSIndexPath?
    //定义模型
    var iconImage:UIImage?{
        didSet{
            
            if iconImage == nil{//没有照片,显示添加图例
                imageView.image = UIImage(named: "compose_pic_add")
                //隐藏删除键
                deleteBtn.hidden = true
            }else{//显示照片
                
                imageView.image = iconImage
                deleteBtn.hidden = false
                
            }
            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setUpUI(){
        //添加控件
        self.addSubview(imageView)
        //设置属性
        imageView.frame = self.bounds
        
        self.addSubview(deleteBtn)
        //设置约束
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_right).offset(-photoviewMargin)
            make.centerY.equalTo(self.snp_top).offset(photoviewMargin)
        }
    }
    
    @objc private func btnClick() {
        //删除图片,需要一个标记 index
        
        if let itemCount = index?.item{
            
            //cell让collectionView去删除一个图片, 使用代理
            delegate?.deletePhoto(itemCount)
            
        }
        
    }
    
    //懒加载
    private lazy var imageView: UIImageView = UIImageView()
    //取消按键
    private lazy var deleteBtn: UIButton = {
        
        let btn = UIButton(type: UIButtonType.Custom)
        
        btn.setImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        btn.setImage(UIImage(named: "compose_card_delete_highlighted"), forState: .Highlighted)
        
        btn.sizeToFit()
        //添加删除方法
        btn.addTarget(self, action: "btnClick", forControlEvents: .TouchUpInside)
        
        
        return btn
    }()
    //添加图片的按钮
//    private lazy var addBtn: UIButton = {
//        let btn = UIButton(type: UIButtonType.Custom)
//        //设置属性
//        btn.setImage(UIImage(named:"compose_pic_add" ), forState: .Normal)
//        btn.setImage(UIImage(named: "compose_pic_add_highlighted"), forState:.Highlighted)
//        
//        //添加点击事件
//        btn.addTarget(self, action: "addPhoto", forControlEvents: .TouchUpInside)
//        
//        return btn
//    }()
    
}